package com.baidu.ocrgeneralocrdemo;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import androidx.appcompat.app.AppCompatActivity;

import com.baidu.ocrgeneralocrdemo.utils.LogUtil;

import static com.baidu.vis.ocrgeneralocr.Predictor.ImagePixelFormat.IMAGE_PIX_FMT_RGB565_LE;
import static com.baidu.vis.ocrgeneralocr.Predictor.ImagePixelFormat.IMAGE_PIX_FMT_RGB565_BE;
import static com.baidu.vis.ocrgeneralocr.Predictor.ImagePixelFormat.IMAGE_PIX_FMT_RGBA;

public class TestAssetsImageActivity extends AppCompatActivity {
    private static final String TAG = "AssetsImageTestActivity";
    private ImageView imageView = null;
    private TextView assetsImagePredictResult = null;
    private Activity activity = null;
    Button button_test_jpg = null;
    Button button_test_png = null;
    Button button_test_rgba8888 = null;
    Button button_test_rgb565_LE = null;
    Button button_test_rgb565_BE = null;

    Button button_test_batch = null;
    private final String imagePath = "test.jpg";
    private final String imagePath2 = "test1.png";
    private final String imageFolder = "image";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_assets_image);

        activity = this;
        imageView = findViewById(R.id.assets_iamge);
        assetsImagePredictResult = findViewById(R.id.assets_image_predict_result);

        button_test_jpg = findViewById(R.id.bt_assets_image_test_jpg); // jpg数据
        button_test_png = findViewById(R.id.bt_assets_image_test_png); // png数据
        button_test_rgba8888 = findViewById(R.id.bt_assets_rgba8888); // rgba8888
        button_test_rgb565_LE = findViewById(R.id.bt_assets_rgb565_LE); // 小端
        button_test_rgb565_BE = findViewById(R.id.bt_assets_rgb565_BE); // 大端
        button_test_batch = findViewById(R.id.bt_assets_image_test_batch); // 批量

        // 测试jpg数据
        button_test_jpg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap image = getBitmap(activity, imagePath);
                PredictorWrapper.asyncTestOneImage(activity, image, imageView, assetsImagePredictResult, new PredictorResultListener() {
                    @Override
                    public void ResultListener(String result) throws IOException {

                    }
                });
            }
        });

        // 测试png数据
        button_test_png.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap image = getBitmap(activity, imagePath2);
                PredictorWrapper.asyncTestOneImage(activity, image, imageView, assetsImagePredictResult, new PredictorResultListener() {
                    @Override
                    public void ResultListener(String result) throws IOException {

                    }
                });
            }
        });

        // 测试rgba8888数据
        button_test_rgba8888.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                byte[] buffer = getbyteFromAssets("test.rgba");
                int w = 1008;
                int h = 756;
                // 调用预测接口
                String result = PredictorWrapper.asyncTestRGB(buffer, w, h, IMAGE_PIX_FMT_RGBA);
                assetsImagePredictResult.setText(result);
                LogUtil.e(result);
            }
        });

        // 测试rgba565小端数据
        button_test_rgb565_LE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                while (true) {
                byte[] buffer = getbyteFromAssets("le.rgb");
                int w = 1008;
                int h = 756;
                // 调用预测接口
                String result = PredictorWrapper.asyncTestRGB(buffer, w, h, IMAGE_PIX_FMT_RGB565_LE);
                assetsImagePredictResult.setText(result);
                LogUtil.e(result);
//                }
            }
        });

        // 测试rgba565大端数据
        button_test_rgb565_BE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                while (true){
                byte[] buffer = getbyteFromAssets("be.rgb");
                int w = 1008;
                int h = 756;
                // 调用预测
                String result = PredictorWrapper.asyncTestRGB(buffer, w, h, IMAGE_PIX_FMT_RGB565_BE);
                assetsImagePredictResult.setText(result);
                LogUtil.e(result);
//                }

            }
        });

        // 测试批量图片数据
        button_test_batch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            // 批量数据测试 由于加载图片太多 内存来不及回收 会导致程序异常crash ！！！！！！！！
                            String[] files = getResources().getAssets().list(imageFolder);
                            for (int i = 0; i < files.length; i++) {
                                Bitmap image = getBitmap(activity, imageFolder + "/" + files[i]);
                                Log.e(TAG, "Start syncTestOneImage " + files[i]);
                                String result = PredictorWrapper.syncTestOneImage(activity, image,
                                        imageView, assetsImagePredictResult);
                                Log.e(TAG, "Start saveResule " + i + files[i] + ".txt  " + result + "\n");

                                saveResule(files[i] + ".txt", result);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            return;
                        }
                    }
                };
                thread.start();
            }
        });
    }


    // 获取数据流
    public byte[] getbyteFromAssets(String fileName) {

        byte[] buffer = null;
        try {
            InputStream is = getResources().getAssets().open(fileName);
            int length = is.available();
            buffer = new byte[length];
            is.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public void saveResule(String fileName, String content) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Log.e(TAG, "SDcard not exist");
            return;
        }

        String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();
        File fileDir = new File(sdpath + "/testresult_v3.5_mode");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File file = new File(fileDir, fileName);
        createFile(file);
        write2File(file, content);
    }

    private File createFile(File file) {
        if (file.exists() && file.isFile()) {
            return file;
        } else {
            try {
                if (file.createNewFile()) {
                    return file;
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    private void write2File(File file, String data) {
        OutputStream ou = null;
        try {
            ou = new FileOutputStream(file);
            byte[] buffer = data.getBytes();
            ou.write(buffer);
            ou.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ou != null) {
                    ou.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static Bitmap getBitmap(Context context, String imageName) {
        InputStream is = null;
        try {
            AssetManager assetManager = context.getResources().getAssets();
            is = assetManager.open(imageName);
            return BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
